﻿//N叉树的层序遍历(medium): https://leetcode.cn/problems/n-ary-tree-level-order-traversal/
/*
// Definition for a Node.
class Node {
public:
    int val;
    vector<Node*> children;

    Node() {}

    Node(int _val) {
        val = _val;
    }

    Node(int _val, vector<Node*> _children) {
        val = _val;
        children = _children;
    }
};
*/

class Solution {
public:
    vector<vector<int>> levelOrder(Node* root) {
        queue<Node*> q;
        vector<vector<int>> ret;
        if(!root)  return ret;
        q.push(root);
        while (!q.empty()) {
            int count = q.size();
            vector<int> v;
            while (count--) 
            {
                Node* front = q.front();
                v.push_back(front->val);
                q.pop();
                for (auto x : front->children) {
                    q.push(x);
                }
            }
            ret.push_back(v);
        }
        return ret;
    }
};

//二叉树的锯齿形层序遍历(medium): https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
        vector<vector<int>> ret;
        if(!root)    return ret;
        queue<TreeNode*> q;
        q.push(root);
        int k=1;  //奇数不要管，偶数颠倒
        while(!q.empty())
        {
            int count=q.size();
            vector<int> tmp;
            while(count--)
            {
                TreeNode* front=q.front();
                tmp.push_back(front->val);
                q.pop();
                if(front->left)  q.push(front->left);
                if(front->right)  q.push(front->right);
            }
            if(k%2==1)   
            {
                ret.push_back(tmp);
            }
            else
            {
                reverse(tmp.begin(),tmp.end());
                ret.push_back(tmp);
            }
            k++;
        }
        return ret;
    }
};